
import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/views/main/Main.vue'
import User from '@/views/system/User.vue'
import Role from '@/views/system/Role.vue'
import Permission from '@/views/system/Permission.vue'
import FixedResponse from '@/views/system/FixedResponse.vue'
import GasFired from '@/views/sim-intel/GasFired.vue'
import MapDashboard from '@/views/main/MapDashboard.vue'
import HeatmapDashboard from '@/views/main/HeatmapDashboard.vue'
import PowerCanvas from '@/views/sim-intel/PowerCanvas.vue'
import VoiceTest from '@/views/main/VoiceTest.vue'
import Login from '@/views/Login.vue'

Vue.use(Router)

const router = new Router({
  // Use default hash mode to avoid server configuration for local dev
  routes: [
    { path: '/', redirect: '/main' },
    {
      path: '/login',
      name: 'login',
      meta: { title: 'Login' },
      component: Login
    },
    {
      path: '/main',
      name: 'main',
      meta: { title: 'Dashboard' },
      component: Main,
      children: [
        { path: 'user', name: 'user', component: User, meta: { title: 'User Management' } },
        { path: 'role', name: 'role', component: Role, meta: { title: 'Role Management' } },
        { path: 'permission', name: 'permission', component: Permission, meta: { title: 'Permission Management' } },
        { path: 'fixed-response', name: 'fixed-response', component: FixedResponse, meta: { title: 'Fixed Response Management' } },
        { path: 'simulation', name: 'simulation', component: GasFired, meta: { title: 'Generator Unit' } },
        { path: 'map', name: 'map', component: MapDashboard, meta: { title: 'Map' } },
        { path: 'heatmap', name: 'heatmap', component: HeatmapDashboard, meta: { title: 'Solar Energy Heatmap' } },
        { path: 'power-canvas', name: 'power-canvas', component: PowerCanvas, meta: { title: 'Power Canvas' } },
        { path: 'voice-test', name: 'voice-test', component: VoiceTest, meta: { title: 'Voice Test' } }
      ]
    },
    {
      path: '*',
      redirect: '/'
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }
  const token = window.localStorage.getItem('token')
  if (!token && to.path !== '/login') {
    return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  next()
})

export default router